package cn.dnui_zll731.dnuifood_731zlll.Adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;


public abstract class RecyclerViewAdapter<VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> {

    protected int layoutResource;
    protected Context context;
    protected List data = new ArrayList();
    protected LayoutInflater layoutInflater;

    public RecyclerViewAdapter(Context context,List data,int layoutResource){
        this.layoutResource = layoutResource;
        this.context = context;
        this.data.addAll(data);
        layoutInflater = LayoutInflater.from(context);
    }



    @Override
    public VH onCreateViewHolder(ViewGroup parent, int viewType) {
        if (getClass().getGenericSuperclass() instanceof ParameterizedType){
            ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();
            Class cla = (Class)parameterizedType.getActualTypeArguments()[0];
            View view = layoutInflater.inflate(layoutResource,parent,false);
            try{
                Constructor<VH> constructor = cla.getConstructor(View.class);
                return constructor.newInstance(view);
            }catch (InstantiationException e){
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }

        return null;
//        View view = LayoutInflater.from(parent.getContext()).inflate(layoutResource,parent,false);
//        return new VH(view);

    }
    public void setData(List data){
        this.data.clear();
        this.data.addAll(data);
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return data == null ? 0:data.size();
    }
}
